package com.xiaoqiudong.forum.exception;

import com.xiaoqiudong.forum.common.AppResult;
import com.xiaoqiudong.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-22
 * Time:15:05
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult handlerApplicationException(ApplicationException e){
        //打印异常
        e.printStackTrace();
        //记录日志
        log.error(e.getMessage());
        if (e.getErrorResult() != null ){
            return e.getErrorResult();
        }
        //非空检验
        if (e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.fail(ResultCode.ERROR_SERVICES);
        }
        return AppResult.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult exceptionHandler(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        //非空检验
        if (e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.fail(ResultCode.ERROR_SERVICES);
        }
        return AppResult.fail(e.getMessage());
    }
}
